package util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MybatisTools {
	private static SqlSessionFactory factory = null;
	private static SqlSession session = null;
	
	public static void init() {
		String resource = "mybatis-config.xml";
		try {
			InputStream in = Resources.getResourceAsStream(resource);
			factory = new SqlSessionFactoryBuilder().build(in);
			session = factory.openSession(true);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static SqlSession getSqlSession() {
		if (session == null)
			init();
		return session;
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T getMapper(Class<?> type) {
		try {
			if (session == null || session.getConnection().isClosed())
				init();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return (T) session.getMapper(type);
	}
}
